/**
 * Copyright [2019] [LiBo/Alex of copyright liboware@gmail.com ]
 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.hyts.infodb.metrics.shutdown;

import com.hyts.infodb.enums.SystemConfiguration;
import lombok.extern.slf4j.Slf4j;
import org.apache.catalina.connector.Connector;
import org.springframework.boot.web.embedded.tomcat.TomcatConnectorCustomizer;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextClosedEvent;

import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * @project-name:infodb
 * @package-name:com.hyts.infodb.metrics.shutdown
 * @author:LiBo/Alex
 * @create-date:2020-01-16 19:01
 * @copyright:libo-alex4java
 * @email:liboware@gmail.com
 * @description: 关闭定义操作配置类
 */

@Slf4j
public class ShutdownConfiguration implements TomcatConnectorCustomizer, ApplicationListener<ContextClosedEvent> {


    private volatile Connector connector;


    @Override
    public void customize(Connector connector) {
        this.connector = connector;
    }

    @Override
    public void onApplicationEvent(ContextClosedEvent contextClosedEvent) {
        this.connector.pause();
        Executor executor = this.connector.getProtocolHandler().getExecutor();
        if (executor instanceof ThreadPoolExecutor) {
            try {
                log.warn("WEB 应用准备关闭");
                ThreadPoolExecutor threadPoolExecutor = (ThreadPoolExecutor) executor;
                threadPoolExecutor.shutdown();
                if (!threadPoolExecutor.awaitTermination(SystemConfiguration.DEFAULT_SHUTDOWN_TIMEOUT, TimeUnit.SECONDS)) {
                    log.warn("WEB 应用等待关闭超过最大时长{}秒，将进行强制关闭!",SystemConfiguration.DEFAULT_SHUTDOWN_TIMEOUT);
                    threadPoolExecutor.shutdownNow();
                    if (!threadPoolExecutor.awaitTermination(SystemConfiguration.DEFAULT_SHUTDOWN_TIMEOUT, TimeUnit.SECONDS)) {
                        log.error("WEB应用关闭失败!");
                    }
                }
            } catch (InterruptedException ex) {
                Thread.currentThread().interrupt();
            }
        }
    }
}
